/**
 * Created by LiH on 2018/7/19.
 */
import axios from 'axios'
import ZCLoadingPlugin from './ZCLoading'
import ZCAlertPlugin from './ZCAlert'

const HOST = `http://${window.location.host}/`;
const request = axios.create({baseURL: HOST});

request.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';

function handleRequestError(error) {
  // Do something with request error
  console.error('request error:\n' + error.message);
  return Promise.reject(error);
}

function handleResponseError(error) {
  // Do something with response error
  if (axios.isCancel(error)) {
    console.log('Request canceled', error.message);
  } else if (error.response) {
    // The request was made and the server responded with a status code
    // that falls out of the range of 2xx
    Vue.$ZCAlert.show({
      title: error.response.status === 500 ? '服务器错误' : '网络错误',
      content: error.response.status + ':' + error.response.statusText
    });
    //console.error(error.response.headers)
  } else if (error.request) {
    // The request was made but no response was received
    // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
    // http.ClientRequest in node.js
    Vue.$ZCAlert.show({
      title: '服务器无响应',
      content: ''
    });
    console.error(error.request);
  } else {
    // Something happened in setting up the request that triggered an Error
    console.error('Set up request:\n' + error.message)
  }
  return Promise.reject(error);
}

// 请求计数，用于loading显示控制
let requestCount = 0;

/*
 * 带loading的请求
 */
request.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    if(config.loading) {
      ++requestCount;
      console.log('requestCount:', requestCount);
      requestCount === 1 && Vue.$ZCLoading.show({
        wxLoading: true,
        desc: '努力加载中……'
      });
    }
    return config;
  },
  handleRequestError
);

function closeLoading() {
  --requestCount;
  if(requestCount <= 0) {
    requestCount = 0;
    Vue.$ZCLoading.hide();
    console.log('requestCount:', requestCount);
  }
}

request.interceptors.response.use(
  function (response) {
    // Do something with response data
    closeLoading();
    return response;
  },
  function (error) {
    // Do something with response error
    closeLoading();
    return handleResponseError(error);
  }
);

export default {
  install(Vue, options) {
    if (!Vue.$ZCLoading) {
      Vue.use(ZCLoadingPlugin)
    }

    if (!Vue.ZCAlert) {
      Vue.use(ZCAlertPlugin)
    }

    if (options && options.HOST) {
      request.defaults.baseURL = options.HOST;
    }

    Vue.prototype.$requestWithLoading = Vue.prototype.$request = request;
    Vue.$requestWithLoading = Vue.$request = request;
    Vue.mixin({
      created() {
        this.$requestWithLoading = this.$request = request;
      }
    })
  }
}

export {request}
